﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;


namespace Chenxin.Lib.House.DAL
{
    public class DataDictionary
    {
        public DataDictionary() { }

        #region  成员方法
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public static bool Exists(Guid RecordId)
        {
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from DataDictionary where RecordId=@RecordId ");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "RecordId", DbType.Guid, RecordId);
            int cmdresult;
            object obj = db.ExecuteScalar(dbCommand);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public static bool Exists(string strwhere)
        {
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            string strSql = string.Format("select count(1) from DataDictionary where {0}", strwhere);
            DbCommand dbCommand = db.GetSqlStringCommand(strSql);
            int cmdresult;
            object obj = db.ExecuteScalar(dbCommand);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public static void Add(Chenxin.Lib.House.Entity.DataDictionary model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into DataDictionary(");
            strSql.Append("ItemKey,ItemValue,ItemType,ItemIndex,CityId,City,CompanyId,Company)");

            strSql.Append(" values (");
            strSql.Append("@ItemKey,@ItemValue,@ItemType,@ItemIndex,@CityId,@City,@CompanyId,@Company)");
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "ItemKey", DbType.AnsiString, model.ItemKey);
            db.AddInParameter(dbCommand, "ItemValue", DbType.AnsiString, model.ItemValue);
            db.AddInParameter(dbCommand, "ItemType", DbType.Int32, model.ItemType);
            db.AddInParameter(dbCommand, "ItemIndex", DbType.Int32, model.ItemIndex);
            db.AddInParameter(dbCommand, "CityId", DbType.Guid, model.CityId);
            db.AddInParameter(dbCommand, "City", DbType.AnsiString, model.City);
            db.AddInParameter(dbCommand, "CompanyId", DbType.Guid, model.CompanyId);
            db.AddInParameter(dbCommand, "Company", DbType.AnsiString, model.Company);
            db.ExecuteNonQuery(dbCommand);
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public static void Update(Chenxin.Lib.House.Entity.DataDictionary model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update DataDictionary set ");
            strSql.Append("ItemKey=@ItemKey,");
            strSql.Append("ItemValue=@ItemValue,");
            strSql.Append("ItemType=@ItemType,");
            strSql.Append("ItemIndex=@ItemIndex,");
            strSql.Append("CityId=@CityId,");
            strSql.Append("City=@City");
            strSql.Append("CompanyId=@CompanyId,");
            strSql.Append("Company=@Company");
            strSql.Append(" where RecordId=@RecordId ");
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "RecordId", DbType.Guid, model.RecordId);
            db.AddInParameter(dbCommand, "ItemKey", DbType.AnsiString, model.ItemKey);
            db.AddInParameter(dbCommand, "ItemValue", DbType.AnsiString, model.ItemValue);
            db.AddInParameter(dbCommand, "ItemType", DbType.Int32, model.ItemType);
            db.AddInParameter(dbCommand, "ItemIndex", DbType.Int32, model.ItemIndex);
            db.AddInParameter(dbCommand, "CityId", DbType.Guid, model.CityId);
            db.AddInParameter(dbCommand, "City", DbType.AnsiString, model.City);
            db.AddInParameter(dbCommand, "CompanyId", DbType.Guid, model.CompanyId);
            db.AddInParameter(dbCommand, "Company", DbType.AnsiString, model.Company);
            db.ExecuteNonQuery(dbCommand);

        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public static void Delete(Guid RecordId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from DataDictionary ");
            strSql.Append(" where RecordId=@RecordId ");
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "RecordId", DbType.Guid, RecordId);
            db.ExecuteNonQuery(dbCommand);

        }



        /// <summary>
        /// 删除多条数据
        /// </summary>
        public static void Delete(string RecordIdList)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from DataDictionary ");
            strSql.Append(" where RecordId in @RecordIdList ");
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "RecordIdList", DbType.Guid, RecordIdList);
            db.ExecuteNonQuery(dbCommand);

        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public static Chenxin.Lib.House.Entity.DataDictionary GetModel(Guid RecordId)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select RecordId,ItemKey,ItemValue,ItemType,ItemIndex,CityId,City,CompanyId,Company from DataDictionary ");
            strSql.Append(" where RecordId=@RecordId ");
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "RecordId", DbType.Guid, RecordId);
            Entity.DataDictionary model = null;
            using (IDataReader dataReader = db.ExecuteReader(dbCommand))
            {
                if (dataReader.Read())
                {
                    model = ReaderBind(dataReader);
                }

                dataReader.Close();
                dataReader.Dispose();
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public static DataSet GetList(string strWhere, string strOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select RecordId,ItemKey,ItemValue,ItemType,ItemIndex,CityId,City,CompanyId,Company ");
            strSql.Append(" FROM DataDictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            if (strOrder.Trim() != "")
            {
                strSql.Append(" Order by " + strOrder);
            }
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");
            return db.ExecuteDataSet(CommandType.Text, strSql.ToString());
        }

        /*
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("UP_GetRecordByPage");
            db.AddInParameter(dbCommand, "tblName", DbType.AnsiString, "DataDictionary");
            db.AddInParameter(dbCommand, "fldName", DbType.AnsiString, "ID");
            db.AddInParameter(dbCommand, "PageSize", DbType.Int32, PageSize);
            db.AddInParameter(dbCommand, "PageIndex", DbType.Int32, PageIndex);
            db.AddInParameter(dbCommand, "IsReCount", DbType.Boolean, 0);
            db.AddInParameter(dbCommand, "OrderType", DbType.Boolean, 0);
            db.AddInParameter(dbCommand, "strWhere", DbType.AnsiString, strWhere);
            return db.ExecuteDataSet(dbCommand);
        }*/

        /// <summary>
        /// 获得数据列表（比DataSet效率高，推荐使用）
        /// </summary>
        /// <param name="strWhere">where 条件</param>
        /// <param name="strOrder">排序条件</param>
        /// <returns></returns>
        public static List<Chenxin.Lib.House.Entity.DataDictionary> GetListArray(string strWhere, string strOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select RecordId,ItemKey,ItemValue,ItemType,ItemIndex,CityId,City,CompanyId,Company ");
            strSql.Append(" FROM DataDictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }

            if (strOrder.Trim() != "")
            {
                strSql.Append(" Order By " + strOrder);
            }

            List<Entity.DataDictionary> list = new List<Entity.DataDictionary>();
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");
            using (IDataReader dataReader = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                while (dataReader.Read())
                {
                    list.Add(ReaderBind(dataReader));
                }

                dataReader.Close();
                dataReader.Dispose();
            }
            return list;
        }


        /// <summary>
        /// 对象实体绑定数据
        /// </summary>
        public static Entity.DataDictionary ReaderBind(IDataReader dataReader)
        {
            Entity.DataDictionary model = new Entity.DataDictionary();
            object ojb;
            ojb = dataReader["RecordId"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.RecordId = new Guid(ojb.ToString());
            }
            model.ItemKey = dataReader["ItemKey"].ToString();
            model.ItemValue = dataReader["ItemValue"].ToString();
            ojb = dataReader["ItemType"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.ItemType = (int)ojb;
            }
            ojb = dataReader["ItemIndex"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.ItemIndex = (int)ojb;
            }
            ojb = dataReader["CityId"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CityId = new Guid(ojb.ToString());
            }
            model.City = dataReader["City"].ToString();


            ojb = dataReader["CompanyId"];
            if (ojb != null && ojb != DBNull.Value)
            {
                model.CompanyId = new Guid(ojb.ToString());
            }
            model.Company = dataReader["Company"].ToString();
            return model;
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="fieldList">需查询的字段，以','分隔</param>
        /// <param name="strWhere">查询条件</param>
        /// <param name="orderField">排序字段</param>
        /// <param name="pageIndex">当前查询的页</param>
        /// <param name="pageSize">当前页需要显示的记录数</param>
        /// <returns></returns>
        public static DataSet GetList(string fieldList, string strWhere, string orderField, int pageIndex, int pageSize, bool doCount)
        {
            Database db = DatabaseFactory.CreateDatabase("Chenxin_House");
            DbCommand dbCommand = db.GetStoredProcCommand("PagerMultiTable");
            db.AddInParameter(dbCommand, "PageIndex", DbType.Int32, pageIndex);
            db.AddInParameter(dbCommand, "PageSize", DbType.Int32, pageSize);
            db.AddInParameter(dbCommand, "OrderField", DbType.AnsiString, orderField);
            db.AddInParameter(dbCommand, "TableName", DbType.AnsiString, "v_DataDictionary");
            db.AddInParameter(dbCommand, "StrWhere", DbType.AnsiString, strWhere);
            db.AddInParameter(dbCommand, "FieldList", DbType.AnsiString, fieldList);
            db.AddInParameter(dbCommand, "TableFieldList", DbType.AnsiString, fieldList);
            db.AddInParameter(dbCommand, "DoCount", DbType.Boolean, doCount);
            return db.ExecuteDataSet(dbCommand);
        }
        
        /// <summary>
        /// 获取板块的ItemIndex
        /// </summary>
        /// <param name="regionId">区域的RecordId</param>
        /// <param name="cityid">城市ID</param>
        /// <param name="itemKey">ItemKey</param>
        /// <returns></returns>
        public static int GetBlockItemIndex(int regionIndex, Guid cityid, string itemKey)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("select isnull(max(itemindex),'{0}000') from DataDictionary where ItemKey='{1}'", regionIndex, itemKey);
            strSql.AppendFormat(" and CityId='{0}' and len(itemIndex)>3", cityid);
            strSql.AppendFormat(" and (substring(Convert(varchar(50), itemIndex), 1 ,len(itemIndex)-3))='{0}'",regionIndex);


            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");
            DataSet ds = db.ExecuteDataSet(CommandType.Text, strSql.ToString());

            if (ds.Tables.Count == 1)
            {
                if (ds.Tables[0].Rows.Count == 1)
                {
                    return Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[0]) + 10;
                }
                else
                {
                    return Convert.ToInt32(regionIndex.ToString() + "10");
                }
            }
            return Convert.ToInt32(regionIndex.ToString() + "10");

        }


        /// <summary>
        /// 获取BlockIndex
        /// </summary>
        /// <param name="regionId">区域的RecordId</param>
        /// <returns></returns>
        public static int GetBlockItemIndex(int regionIndex)
        {
            return GetItemIndex(regionIndex,"System.Block");
        }

        /// <summary>
        /// 获取ItemIndex
        /// </summary>
        /// <param name="regionId">区域的RecordId</param>
        /// <param name="itemKey">ItemKey</param>
        /// <returns></returns>
        public static int GetItemIndex(int regionIndex, string itemKey)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("select isnull(max(itemindex),'{0}000') from DataDictionary where ItemKey='{1}'", regionIndex, itemKey);
            strSql.AppendFormat(" and (substring(Convert(varchar(50), itemIndex), 1 ,len(itemIndex)-3))='{0}'", regionIndex);


            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");
            DataSet ds = db.ExecuteDataSet(CommandType.Text, strSql.ToString());

            if (ds.Tables.Count == 1)
            {
                if (ds.Tables[0].Rows.Count == 1)
                {
                    return Convert.ToInt32(ds.Tables[0].Rows[0].ItemArray[0]) + 10;
                }
                else
                {
                    return Convert.ToInt32(regionIndex.ToString() + "10");
                }
            }
            return Convert.ToInt32(regionIndex.ToString() + "10");

        }

        /// <summary>
        /// 根据区域，城市，删除板块
        /// </summary>
        /// <param name="regionIndex"></param>
        /// <param name="cityid"></param>
        public static void DeleteBlock(int regionIndex, Guid cityid)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("delete from DataDictionary where (ItemKey='System.Block' or ItemKey='System.Area')");
            strSql.AppendFormat(" and CityId='{0}' and len(itemIndex)>3", cityid);
            strSql.AppendFormat(" and (substring(Convert(varchar(50), itemIndex), 1 ,len(itemIndex)-3))='{0}'", regionIndex);


            Database db = DatabaseFactory.CreateDatabase("Chenxin_House_Search");

            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.ExecuteNonQuery(dbCommand);
        }

        #endregion  成员方法
    }
}
